<?php
namespace App\Traits;

use App\Http\Lib\Output;
use App\Http\Lib\ErrCodeMsg;
use App\Http\Lib\HttpClient;

trait Response{
    // 自定义借口：输出json
    # code : int|mix  0成功，其他数字表示错误
    # data : mix
    public function o($code = ERROR_OK, $data = ""){
        return response()->make(Output::o($code, $data));
    }

    public function e($code = ERROR_ERR, $data = ""){
        return response()->make(Output::e($code, $data));
    }

    # $msg : int|string
    public function errorPage($msg = ERROR_ERR, $view = 'public-error', $statusCode = 200){
        if(is_integer($msg))
            $msg = ErrCodeMsg::get($msg);

        return $this->simpleView("error/$view", ['error_msg' => $msg], $statusCode);
    }

    public function app_url(){
        // global $is_admin_web;
        // if($is_admin_web)
        //   return env('ADMIN_URL', env('APP_URL'));

        // return env('APP_URL');
        return url('/');
    }

    # 获取用户中心的urls配置
    public function uc_urls(){
        $res = HttpClient::post(sprintf('%s/urls', env('UC_URL')));
        $res = json_decode($res, true);
        if(!$res || $res['errcode'] != 0)
            return false;

        return $res['data'];
    }

    public function view($view = null, $data = [], $mergeData = []) {
        $data['app_url'] = $this->app_url();
        $data['version'] = env('VERSION');
        // $data['uc_url'] = env('UC_INDEX_URL');
        // $data['mc_url'] = env('MC_INDEX_URL');

        # 只有后台才需要获取用户中心的url配置
        global $is_admin_web;
        if($is_admin_web){
            $urls = $this->uc_urls();
            if(!$urls)
                return $this->errorPage('从用户中心获取urls配置失败');

            // dd($urls);
            $data['uc_url'] = $urls['uc_url'];
            $data['mc_url'] = $urls['mc_url'];
            $data['personal_url'] = $urls['personal_url'];
            $data['appcenter_url'] = $urls['appcenter_url'];
        }

        if(empty($data['title']))
            $data['title'] = env('APP_TITLE', 'Freya2.0');

        return view($view, $data, $mergeData);
    }

    public function simpleView($view = null, $data = [], $statusCode = 200){
        $data['app_url'] = $this->app_url();
        $data['version'] = env('VERSION');
        if(empty($data['title']))
            $data['title'] = env('APP_TITLE', 'Freya2.0');

        return response()->view($view, $data, $statusCode);
    }

    public function redirect($routeName, $params = [], $absolute = true){
        $uri = route($routeName, $params, $absolute);
        // dd($uri);
        return redirect($uri);
    }

    public function forceRootUrl($url){
        \URL::forceRootUrl($url);
        \URL::forceScheme(substr($url, 0, strpos($url, ':')));
    }

}